package cn.pconline.autoclub.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Activity;
import cn.pconline.autoclub.entity.ActivityDiary;
import cn.pconline.autoclub.entity.ActivityMember;
import cn.pconline.autoclub.entity.ActivityPic;
import cn.pconline.autoclub.entity.ActivityPlace;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ActivityPicService;
import cn.pconline.autoclub.service.ActivityPlaceService;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.DynaIndexService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.Bread;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.AbstractDyna;
import cn.pconline.autoclub.util.excel.ExcelGenerator;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author 作者 guoqiang
 * @version 2014-1-21
 */
@Controller
public class ActivityController {

    @Autowired
    private ActivityService activityService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ActivityPicService activityPicService;
    @Autowired
    private IntfService intfService;
    @Autowired
	private ActivityPlaceService activityPlaceService;
    @Autowired
    private DynaIndexService dynaIndexService;
    
    private static Logger log = LoggerFactory.getLogger(ActivityController.class);
    private static final int MAX_PAGESIZE = 100;
    private static final int MIN_PAGESIZE = 1;
    //活动创建默认封面图
    private static final String defalutImg = "http://www1.pcauto.com.cn/bbs/cargroup/2014/images/defaultphoto8.jpg";
    private static final int DEFAULT_PAGE_SIZE = 20;//默认分页大小
    private static final int DEFAULT_PRAISE_PAGE_SIZE = 13;//动态详细页点赞用户分页大小 获取点赞用户第一页列表,一页最多13个，页面要求
    private static final int MAX_PAGE_SIZE = 100;
    /**
     * 判断用户是否登录》》是否会员》》是否管理员
     *
     * @param req
     * @param resp
     * @return
     */
    public boolean hasRight(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        User user = userAuth.getUser(req, resp);
        if (user == null || user.getUid() == 0) {
            try {
                resp.sendRedirect(systemConfig.getUcRoot()
                        + "/login.jsp?return="
                        + req.getRequestURL()
                        + "?" + req.getQueryString());
            } catch (IOException ex) {
                log.error("判断用户是否登录》》是否会员》》是否管理员 出错！", ex);
            }
            return false;
        }
        req.setAttribute("user", user);
        ClubMember member = memberService.findMember(user.getUid(), clubId);
        if (member == null || !member.isAdministrator()) {
            try {
                resp.sendError(403);
            } catch (IOException ex) {
                log.error("判断用户是否登录》》是否会员》》是否管理员 出错！", ex);
            }
            return false;
        } else {
            req.setAttribute("member", member);
            return true;
        }
    }
    
    /**
     * 判断活动权限----登录-> 创建 ；活动创建者--》修改
     * @param req
     * @param resp
     * @return
     */
   public boolean hasActivityRight(HttpServletRequest req, HttpServletResponse resp){
	   long activityId = WebUtils.paramLong(req, "activityId", 0);
       User user = userAuth.getUser(req, resp);
       if (user == null || user.getUid() == 0) {
           try {
               resp.sendRedirect(systemConfig.getUcRoot()
                       + "/login.jsp?return="
                       + req.getRequestURL()
                       + "?" + req.getQueryString());
           } catch (IOException ex) {
               log.error("判断用户是否登录》》是否会员》》是否管理员 出错！", ex);
           }
           return false;
       }
       req.setAttribute("user", user);
       if(activityId>0){
    	   Activity activity = activityService.findById(activityId);
    	   if(activity!=null){
    		   if(user.getUid()!=activity.getCreateBy()){
    	            try {
    	                resp.sendError(403);
    	            } catch (IOException ex) {
    	                log.error("判断活动创建者是不是该用户出错！", ex);
    	            }
    	            return false;
    		   }
    	   }
    	   
       }else{
    	   return true;
       }
       return true;
   }
   
   /**
    * 判断活动地点是否正确
    * @param activity
    * @param gatherings
    * @param destinations
    * @param resp
    * @return
    */
   public boolean hasActivityPlaceRight(Activity activity,List<ActivityPlace> gatherings,List<ActivityPlace> destinations,HttpServletResponse resp){
	   if(activity.getType() != Activity.TYPE_OTHER){
		   if (gatherings == null || gatherings.size () <= 0) {
			   errorMsg(resp, "请输入集合地点", "");
               return false;
           }
           if(activity.getType()==Activity.TYPE_DRIVING){ //自驾游判断必须有一个目的地
           	if(destinations== null || destinations.size()<=0){
           	   errorMsg(resp, "自驾游必须有一个目的地", "");
               return false;
           	}

           }
           if(destinations.size() > 10) {
        	   errorMsg(resp, "最多可填写10个目的地点", "");
               return false;
           }
	   }
	   return true;
   }

    /**
     * 活动创建页面跳转
     *
     * @param req
     * @param resp
     * @return Created by guoqiang, 2014-01-22
     */
    @RequestMapping(value = "/activity/add.do", method = RequestMethod.GET)
    public String add(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--getValidClub!", ex);
            }
        }
        this.hasActivityRight(req, resp);
        Activity activity = null;
        String coverImg = defalutImg;
        String picUrlOrigin = "";
        List<ActivityPic> pics = new ArrayList<ActivityPic>();
        boolean isEditTime = false;
        if (activityId > 0) {
            activity = activityService.findById(activityId);
            if (activity == null) {
                try {
                    resp.sendError(404);
                    return null;
                } catch (IOException ex) {
                    log.error("redirect to error page fail--findByactIdClubId!", ex);
                }
            } else {
                if (StringUtils.isNotBlank(activity.getPicUrl())) {
                    coverImg = activity.getPicUrl();
                }
                if (activity.getLongContext() > 0) {
                    activity.setContext(activityService.getTotalActivityTxt(activityId));
                }
                if (activity.getEndDate().getTime() < DateUtils.getNow().getTime()) {
                    isEditTime = true;
                }
                picUrlOrigin = activity.getUrl160x107();	 //活动动态图片
                //活动图片
                pics = activityPicService.listPicsByActivity(activity, "asc" );
                req.setAttribute("createBy", activity.getCreateBy());
                //活动集合地
                List<ActivityPlace> gatherings = activityPlaceService.listPlaceByActivityAndType(activity, ActivityPlace.TYPE_GATHERING);
                if(gatherings!=null && gatherings.size()>0)
                req.setAttribute("gather",gatherings.get(0));
                //活动目的地
                List<ActivityPlace> descriptions = activityPlaceService.listPlaceByActivityAndType(activity, ActivityPlace.TYPE_DESTINATION);
                req.setAttribute("descriptions",descriptions);
            }
        }

        // has no permissions to login
        req.setAttribute("picUrlOrigin", picUrlOrigin);
        req.setAttribute("pics", pics );
        req.setAttribute("coverImg", coverImg);
        req.setAttribute("clubId", clubId);
        req.setAttribute("clubName", club.getName());
        req.setAttribute("activity", activity);
        req.setAttribute("isEditTime", isEditTime);
        req.setAttribute("ZJY",Activity.TYPE_DRIVING);
        req.setAttribute("JH",Activity.TYPE_DINNER);
        req.setAttribute("QT",Activity.TYPE_OTHER);
        ClubController.setClubStyle(req, club.getClubId());
        req.setAttribute("BAIDUMAPAK", systemConfig.getBaiduMapAk());
        return "template/activity/activity_add";
    }

    /**
     * 创建相册
     *
     * @param req
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/activity/addalbum.do", method = RequestMethod.GET)
    public String addalbum(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        req.setAttribute("clubId", clubId);
        return "template/activity/common/create_album";
    }
    

    
    

    /**
     * 活动创建
     *
     * @param req
     * @param resp Created by guoqiang, 2014-01-22
     */
    @RequestMapping(value = "/activity/create.do", method = RequestMethod.POST)
    public void addActivity(HttpServletRequest req, HttpServletResponse resp) {
    	String contString = req.getParameter("context");
    	System.out.println(contString);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        String picUrl = WebUtils.param(req, "picUrlOrigin", "");
        int picWidth = WebUtils.paramInt(req, "picWidth", 0);
        int picHeight = WebUtils.paramInt(req, "picHeight", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
                resp.sendError(404);
                return;
            } catch (IOException ex) {
                log.error("redirect to error page fail--getValidClub!", ex);
            }
        }
        this.hasActivityRight(req, resp);
        Activity activity = this.convertActivity(req);
        List<ActivityPic> activityPics = this.converActivityPics(req);
        if(activityPics.size()>50){
        	errorMsg( resp, "最多可上传50张照片", "");
        	return;
        }
        long activityId = activity.getActivityId();
        String phone = WebUtils.param( req, "phone","").trim();
        //表单验证
        if (this.checkActivity(activity, resp)) {
        	if(this.checkPhone(phone, resp )){
        		//集合地点
        		List<ActivityPlace> gatherings = this.convertActivityPlace(req,ActivityPlace.TYPE_GATHERING);
        		//目的地点
        		List<ActivityPlace> destinations = this.convertActivityPlace(req,ActivityPlace.TYPE_DESTINATION);
        		if(hasActivityPlaceRight( activity, gatherings, destinations, resp )){
                    User user = userAuth.getUser(req, resp);
                    if(user==null || user.getUid()<=0){
                    	errorMsg( resp, "请先登录", "");
                    	return;
                    }
                    if(activity.getCreateBy()<=0){
                    	activity.setCreateBy(user.getUid());
                    }
                    List<ActivityPlace> activityPlaces = null;
                    if(activity.getType()==Activity.TYPE_DINNER){
                    	activityPlaces = gatherings;
                    }
                    if(activity.getType()==Activity.TYPE_DRIVING){
                    	activityPlaces = gatherings;
                    	activityPlaces.addAll(destinations);
                    }
                    if(activity.getType()==Activity.TYPE_OTHER){
                    	activityPlaces = new ArrayList<ActivityPlace>();
                    }
                    
                    //活动地址
                    if(activityPlaces!= null && activityPlaces.size()>0){
                        ActivityPlace whoisPlace = activityPlaces.get(activityPlaces.size()-1);	//取最后一个作为活动地址（优先取最后一个目的地，没有目的地取集合地点）
                        double longitude = whoisPlace.getLongitude();
                        double latitude = whoisPlace.getLatitude();
                        JSONObject areaObject = intfService.getPlaceByLngLli(longitude, latitude);
                		if(areaObject!=null){
                			try {
                				String provinceName = areaObject.getString("pro");
                    			long provinceId = areaObject.getLong("proCode");
                    			String cityName = areaObject.getString("city");
                    			long cityId = areaObject.getLong("cityCode");
                    			activity.setProvinceId(provinceId);
                    			activity.setProvinceName(provinceName);
                    			activity.setCityId(cityId);
                    			activity.setCityName(cityName);
                    			
                			} catch(NullPointerException exception) {
                				log.error("app create Activity : call whois throw Exception, longitude:{}, latitude:{}", longitude,latitude, exception);
                			}
                    	}
                    }
                    
                    if (activity.getActivityId() > 0) {
                        //update
                        activityService.updateActivity(activity);
                        //保存活动集合地，目的地
                        activityPlaceService.deleteAndAddActivityPlace(activityId, activityPlaces);
                        //活动图片
                        activityPicService.deleteAndAddActivityPic( activityId, activityPics );
                        
                    } else {
                        //add
                    	activity.setCreateAt(DateUtils.getNow());
                        activity.setStatus(Activity.STATUS_YES);
                        activityId =activityService.createActivity(activity);
                    	//保存活动集合地，目的地
                        if(!activityPlaces.isEmpty()){
                        	activityPlaceService.batchCreateActivityPlace(activityId, activityPlaces);
                        }
                        //活动图片
                        if(!activityPics.isEmpty()){
                        	activityPicService.batchCreateActivityPic(activityId, activityPics);
                        	
                        }
                        if (activity.getActivityId() > 0) {
                            //发布活动动态
                            AbstractDyna dyna = new AbstractDyna();
                            dyna.setClubId(clubId);
                            dyna.setContent("");//内容直接拿活动信息，这里不需要设置
                            dyna.setCreateBy(activity.getCreateBy());
                            dyna.setCreateName(user.getNickname());
                            dyna.setCreateDate(activity.getCreateAt());
                            dyna.setTargetId(activity.getActivityId());
                            List<DynaImage> img = new ArrayList<DynaImage>();
                            if(StringUtils.isNotBlank(picUrl)&&picWidth>0&&picHeight>0){
                                DynaImage i = new DynaImage();
                                i.setUrl(picUrl);
                                i.setHeight(picHeight);
                                i.setWidth(picWidth);
                                i.setSeq(1);
                                img.add(i);
                            }
                            dynaService.createActivityDyna(dyna, img);
                            
                            // 发起活动发消息通知全体会员
                            List<ClubMember> members = memberService.listMemberByClubId(activity.getClubId());
                            for (ClubMember u : members) {
                                if(u.getUid() != user.getUid()) {
                                    messageService.send(u.getUser(), MessageService.NEW_ACTIVITY,
                                            messageService.assembleUserUrl(user.getUid(), user.getNickname()), messageService.assembleActivityUrl(club.getClubUrl(), activityId, activity.getTitle()));
                                }
                            }

                        }
                    }
                    user.setPhone(phone);
                    userService.updateUser(user,"phone");
                    req.setAttribute("clubId", clubId);
                    successMsg(resp, activity.getActivityId() + "");
        		}
        	}
        }
    }

    /**
     * 活动列表
     *
     * @param req
     * @param resp
     * @return Created by guoqiang, 2014-01-22
     */
    @RequestMapping(value = "/activity/list.do", method = RequestMethod.GET)
    public String listActivity(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 10, MIN_PAGESIZE, MAX_PAGESIZE);
        if (club == null || pageNo < 1) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--getValidClub!", ex);
            }
        }

        User user = userAuth.getUser(req, resp);
        ClubMember member = memberService.findMember(user.getUid(), clubId);
        List<Activity> listActivity = activityService.listActivity(member == null ? 0 : member.getId(), clubId, 2, false, true);
        //活动日记
        Pager<ActivityDiary> pager = activityService.pageActivityDiary(0, clubId, pageNo, pageSize);
        WebUtils.checkPageMaxNo(resp, pageNo, pager.getPageCount());
//    	List<Activity> listMyAct = null;
//    	if(member != null && clubId >0){
//    		listMyAct = activityService.listMyJoinActivity(member.getId(),clubId);
//    	}
        List<Bread> breadList = new ArrayList<Bread>(2);
        breadList.add(new Bread(systemConfig.getRoot() + "/" + req.getParameter("desc") + "/activity/", "活动"));

        req.setAttribute("breadList", breadList);
        req.setAttribute("club", club);
        req.setAttribute("listActivity", listActivity);
        req.setAttribute("user", user);
        req.setAttribute("clubId", clubId);
        req.setAttribute("member", member);
        req.setAttribute("pager", pager);
//        req.setAttribute("listMyAct", listMyAct);
        //服务器时间，用于活动报名截止时间倒计时
        req.setAttribute("currentDatetime", new Date().getTime());
        ClubController.setClubStyle(req, club.getClubId());
        return "template/activity/activity_list";
    }

    /**
     * 活动列表 不带日记
     *
     * @param req
     * @param resp
     * @return Created by guoqiang, 2014-01-22
     */
    @RequestMapping(value = "/activitys/list.do", method = RequestMethod.GET)
    public String listActivitys(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 10, MIN_PAGESIZE, MAX_PAGESIZE);
        if (club == null || pageNo < 1) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--getValidClub!", ex);
            }
        }
        User user = userAuth.getUser(req, resp);
        ClubMember member = memberService.findMember(user.getUid(), clubId);

        Pager<Activity> pager = activityService.pageForList(member == null ? 0 : member.getId(), clubId, false, pageNo, pageSize);
        WebUtils.checkPageMaxNo(resp, pageNo, pager.getPageCount());
        List<Bread> breadList = new ArrayList<Bread>(2);
        breadList.add(new Bread(systemConfig.getRoot() + "/" + req.getParameter("desc") + "/activitys/", "活动列表"));
        
        req.setAttribute("breadList", breadList);
        req.setAttribute("club", club);
        req.setAttribute("user", user);
        req.setAttribute("clubId", clubId);
        req.setAttribute("member", member);
        req.setAttribute("pager", pager);

        //服务器时间，用于活动报名截止时间倒计时
        req.setAttribute("currentDatetime", new Date().getTime());
        ClubController.setClubStyle(req, club.getClubId());

        return "template/activity/activity_listDetail";
    }

    /**
     * 活动详情
     *
     * @param req
     * @param resp
     * @return Created by guoqiang, 2014-01-24
     */
    @RequestMapping(value = "/activity/detail.do", method = RequestMethod.GET)
    public String detailActivity(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", DEFAULT_PAGE_SIZE, 1, MAX_PAGE_SIZE);
        Club club = clubService.getValidClub(clubId);
        Activity activity = activityService.findById(activityId);
        User user = userAuth.getUser(req, resp);
        ClubMember member = memberService.findMember(user.getUid(), clubId);
        if (activity == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--findByactIdClubId!", ex);
            }
        }
        //完整内容
        if (activity != null) {
            activity.setFullContent(activityService.getTotalActivityTxt(activityId));
            activity.setUserActivityStatus(activityService.getDetailActivityStatus(member == null ? 0 : member.getId(), activityId).get("code"));
        }
        //是否为活动创建者
        boolean isCreator =false;
        if(user.getUid() == activity.getCreateBy()){
        	isCreator = true;
        }
//    	List<Activity> listMyAct = null;
        int isSignUp = 0;//是否报名
        if (member != null && clubId > 0) {
            //我参加的未结束活动
//    		listMyAct = activityService.listMyJoinActivity(member.getId(),clubId);
            if (activityService.isSignUp(activityId, member.getId()) != null) {
                isSignUp = 1;
            }
        }
        //热门活动
//        List<Activity> listHostAct = activityService.listActivity(clubId,0,true);
        //该活动参加的人员列表
        List<ActivityMember> listMember = activityService.listMemberByActivitiId(activityId, ActivityMember.STATUS_PASS);
        List<ActivityMember> listApply = activityService.listMemberByActivitiId(activityId, ActivityMember.STATUS_APPLY);
        //活动图片
        List<ActivityPic> activityPics = activityPicService.listPicsByActivity( activity, "asc" );
        if(activityPics!=null){
        	req.setAttribute("pics", activityPics);
        }
        //用户相关
        boolean isClubAdmin = false;
        boolean isPresident = false;
        boolean isMember = false;
        if (user.getUid() != 0L) {
            if (member != null) {
                isClubAdmin = member.isAdministrator();
                isPresident = member.isAdmin();
            }
        }
        req.setAttribute("user", user);
        req.setAttribute("isMember", isMember);
        req.setAttribute("isLogin", user.getUid() > 0);
        req.setAttribute("isPresident", isPresident);
        req.setAttribute("isClubAdmin", isClubAdmin);
        
        //活动动态
        DynaInfo dynaInfo = activityService.getDynaById(activity);
        if(dynaInfo!=null){
        	Pager<User> praisePager = dynaService.getPraiseUserList(dynaInfo.getDynaInfoId(), 1,DEFAULT_PRAISE_PAGE_SIZE);
        	req.setAttribute("dynaInfo", dynaInfo);
        	req.setAttribute("praisePager", praisePager);
        	//动态回复
            Pager<DynaReply> pager = dynaService.getReplyListByDynaInfoId(dynaInfo.getDynaInfoId(), pageNo, pageSize);
            req.setAttribute("pager", pager);
            
            int praseCount = dynaService.getPraseCountByUid(dynaInfo.getDynaInfoId(), user.getUid());
            if (praseCount == 1) {
                req.setAttribute("isPraise", true);
            } else {
            	req.setAttribute("isPraise", false);
            }
        }
        req.setAttribute("isCreator", isCreator);
        req.setAttribute("isSignUp", isSignUp);
        req.setAttribute("member", member);
        req.setAttribute("clubId", clubId);
        req.setAttribute("club", club);
        req.setAttribute("activity", activity);
        req.setAttribute("listMember", listMember);
        req.setAttribute("listApply", listApply);
        //服务器时间，用于活动报名截止时间倒计时
        req.setAttribute("currentDatetime", new Date().getTime());
        ClubController.setClubStyle(req, club.getClubId());

        return "template/activity/activity_detail";
    }

    /**
     * 活动报名审核/拒绝 action 1审核操作 -1拒绝操作
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/activity/auditActivity.do", method = RequestMethod.POST)
    public void auditActivity(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long targetId = WebUtils.paramLong(req, "targetId", 0);
        int action = WebUtils.paramInt(req, "action", 0);
        User user = userAuth.getUser(req, resp);
        JSONObject json = new JSONObject();
        Activity activity = activityService.findById(activityId);
        if (user != null) {
            if (activity != null) {
                Club club = clubService.getValidClub(activity.getClubId());
                if (user.getUid() == activity.getCreateBy()) {
                    ActivityMember member = activityService.getApplyByUidAid(targetId, activityId, ActivityMember.STATUS_APPLY);
                    ClubMember clubMember = memberService.find(targetId);
                    if (member != null) {
                        if (action == ActivityMember.STATUS_PASS || action == ActivityMember.STATUS_DELETE) {
                            if (action == ActivityMember.STATUS_PASS && (activity.getMaxJoin() > 0 && activity.getMaxJoin() < (activity.getJoinNum() + member.getJoinNum()))) {
                                json.put("message", "审核失败，人数超过上限");
                                json.put("code", 1004);
                            } else {
                                if (activityService.editApplyBy(action, member, activity.getClubId())) {
                                    json.put("code", 0);
                                    String msg = "审核成功";
                                    if (action == ActivityMember.STATUS_DELETE) {
                                        User createUser = userService.findUser(activity.getCreateBy());
                                        msg = "拒绝成功";
                                        
                                        //给申请人发送拒绝消息
                                        messageService.send(userService.findUser(clubMember.getUid()), MessageService.ACT_APPLY_FALSE, 
                                                messageService.assembleUserUrl(createUser.getUid(), createUser.getNickname()));
                                    } else {
                                        //给申请人发送审核通过消息
                                        messageService.send(userService.findUser(clubMember.getUid()), MessageService.ACT_APPLY_PASS, 
                                                messageService.assembleActivityUrl(club.getClubUrl(), activityId, activity.getTitle()));
                                    }

                                    json.put("message", msg);
                                } else {
                                    String msg = "审核失败";
                                    if (action == ActivityMember.STATUS_DELETE) {
                                        msg = "拒绝失败";
                                    }
                                    json.put("message", msg);
                                    json.put("code", 1);
                                }
                            }
                        } else {
                            json.put("message", "指令错误");
                            json.put("code", 1002);
                        }
                    } else {
                        json.put("message", "该申请已被处理");
                        json.put("code", 1004);
                    }
                } else {
                    json.put("code", 1001);
                    json.put("message", "您不是活动发布者，只有发布者才能进行该操作哦！");
                }
            } else {
                json.put("code", 1002);
                json.put("message", "活动不存在");
            }
        } else {
            json.put("code", 1003);
            json.put("message", "用户未登录");
        }
        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("auditActivity fail!", ex);
        }
    }

    /**
     * 删除活动
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/activity/delActivity.do", method = RequestMethod.POST)
    public void delActivity(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        User user = userAuth.getUser(req, resp);
        Long userId = user.getUid();
        
         //判断活动是否存在
        Activity activity = activityService.findById(activityId);
        if(activity == null) {
                errorMsg(resp, "该活动不存在", "");
        	return;
        }
        
        long createBy = activity.getCreateBy();
        
         //获得车友会信息
        Club club = clubService.getValidClub(clubId);
        if(club == null) {
            errorMsg(resp, "该车友会不存在", "");
            return;
        }
        
        if (activityId < 1) {
            try {
                resp.sendError(404);
                return;
            } catch (IOException ex) {
                log.error("redirect to error page fail--activityId!", ex);
            }
        }
        this.hasRight(req, resp);
        List<ActivityMember> membersPass = activityService.listMemberByActivitiId(activityId, 1); //已审
        List<ActivityMember> members = activityService.listMemberByActivitiId(activityId, 0);  //未审
        int result = activityService.removeActivity(activityId);
        if (result > 0) {
        	//删除活动对应的动态
        	DynaInfo dynaInfo = dynaService.getDynaByTargetId(activity.getCreateAt(),activityId,DynaInfo.TYPE_ACTIVITY);
        	if(dynaInfo != null) {
        		dynaService.deleteClubDyna(activity.getClubId(), dynaInfo.getDynaInfoId());//删除车友会动态索引
        		dynaService.deleteUserDyna(createBy, dynaInfo.getDynaInfoId());//删除车友会用户索引
        		dynaIndexService.deleteDynaIndex( dynaInfo.getDynaInfoId());
        	}
        	
            // 用户已报名还未审核的活动被删除，通知用户
            for (ActivityMember u : members) {
            	//不发给创活动建者自己
            	if(userId == createBy) {
            		continue;
            	}
                 messageService.send(u.getUser(), MessageService.DELETE_ACTIVITY_JOINED,
                            messageService.assembleUserUrl(user.getUid(), user.getNickname()));
            }
            // 用户已报名参加且通过的活动被删除，通知用户
            for (ActivityMember u : membersPass) {
            	//不发给创活动建者自己
            	if(userId == createBy) {
            		continue;
            	}
                 messageService.send(u.getUser(), MessageService.DELETE_ACTIVITY_JOINED,
                            messageService.assembleUserUrl(user.getUid(), user.getNickname()));
            }
            
            //是管理者也是活动发起人，删除活动时不用系统消息
            if(memberService.isClubNormalAdmin(userId, clubId) && userId != createBy){ //是管理者删除活动
                //用户发起的活动被删除，通知用户
                User receiver = userService.findUser(createBy);
                messageService.send(receiver, MessageService.DELETE_ACTIVITY_CREATED,
                        messageService.assembleActivityUrl(club.getClubUrl(), activityId, activity.getTitle()), messageService.assembleUserUrl(user.getUid(), user.getNickname()));
            }
                
            successMsg(resp, "删除成功");
        } else {
            errorMsg(resp, "删除失败", "");
        }
    }

    //TODO 活动相关的要优化下，有点乱！！！
    /**
     * 活动报名相关
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/activity/applyrefused.do", method = RequestMethod.POST)
    public void applyrefused(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long memberId = WebUtils.paramLong(req, "memberId", 0);
        Activity activity = activityService.findById(activityId);
        if (activityId < 1) {
            try {
                resp.sendError(404);
                return;
            } catch (IOException ex) {
                log.error("redirect to error page fail--findByactIdClubId!", ex);
            }
        }
        if (activity == null) {
            errorMsg(resp, "活动不存在", "");
            return;
        }
        String method = WebUtils.param(req, "method", "");
        String message = "报名失败";
        User user = userAuth.getUser(req, resp);
        if (user.getUid() <= 0) {
            errorMsg(resp, "用户未登录", "");
            return;
        }
        ClubMember clubMember = memberService.findMember(memberId);
        if (clubMember == null || clubMember.getUid() != user.getUid()) {//自己才可以报名或者取消
            errorMsg(resp, "没有权限", "");
            return;
        }
        //存在记录则为取消报名否则为报名
        if ("cancel".equals(method)) {
            if (activity.getSignupDate().getTime() >= DateUtils.getNow().getTime()) {
                //存在记录则为取消报名
                if (activityService.deleteActityMember(activityId, memberId) > 0) {
                    activityService.refshActivityJoinNum(activityId, activity.getClubId());
                    message = "取消成功";
                    successMsg(resp, message);
                }
            } else {
                message = "报名时间已截止，不能取消报名";
                errorMsg(resp, message, "");
            }

        } else {
            boolean result = false;
            //报名
            ActivityMember member = this.convertoAcMember(activityId, memberId, req);
            member.setNikename(user.getNickname());
            if (!this.checkAcMember(member, resp)) {
                return;
            }
            if (activity.getMaxJoin() > 0 && activity.getJoinNum() >= activity.getMaxJoin()) {
                message = "报名人数已满，请联系管理员！";
            } else {
                if (activityService.createActityMember(member) > 0) {
                    message = "已提交报名资料，请等待管理员审核。";
                    result = true;

                    //给管理员发送审核消息
                    Club club = clubService.getValidClub(activity.getClubId());
                    if (club != null) {
                        List<ClubMember> listMember = memberService.listAdmins(club.getClubId());
                        String activityUrl = messageService.assembleClubUrl(club.getClubUrl() + "/activity/a" + activityId, activity.getTitle());
                        if (club != null && listMember != null && !listMember.isEmpty()) {
                            for (ClubMember adminMember : listMember) {
                                messageService.send(userService.findUser(adminMember.getUid()), MessageService.ACTIVITY_APPLY, activityUrl, member.getName());
                            }
                        }
                    }
                }
            }
            if (result) {
                successMsg(resp, message);
            } else {
                errorMsg(resp, message, "");
            }

        }
    }

    /**
     * 跳到活动日记
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/activity/todiay.do", method = RequestMethod.GET)
    public String todiay(HttpServletRequest req, HttpServletResponse resp) {
        long diaryId = WebUtils.paramLong(req, "diaryId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        ActivityDiary activityDiary = null;
        if (diaryId > 0) {
            activityDiary = activityService.getDiaryById(diaryId);
        }
        this.hasRight(req, resp);

        req.setAttribute("activityDiary", activityDiary);
        req.setAttribute("diaryId", diaryId);
        req.setAttribute("clubId", clubId);
        return "template/activity/activity_diary";
    }

    /**
     * 活动日记
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping(value = "/activity/adddiary.do", method = RequestMethod.POST)
    public void adddiary(HttpServletRequest req, HttpServletResponse resp) {
        ActivityDiary diary = this.conver2Diary(req);
        if (diary.getClubId() < 1) {
            errorMsg(resp, "参数错误", "");
        }
        this.hasRight(req, resp);

        int retArr = activityService.addActivityDiary(diary);
        if (retArr == -1) {
            //接口返回null数据
            errorMsg(resp, "请输入正确的论坛帖子地址", "1");
        } else if (retArr > 0) {
            //接口返回数据，result=null
            errorMsg(resp, "添加日记失败，请检查后重试", "2");
        } else if (retArr == -2) {
            //修改数据成功
            successMsg(resp, "日记修改成功");
        } else if (retArr == -3) {
            //增加数据成功
            successMsg(resp, "日记添加成功");
        } else {
            //修改日记地址失败
            errorMsg(resp, "地址修改失败", "1");
        }
    }

    /**
     * 日记对象转换
     *
     * @param req
     * @return
     */
    private ActivityDiary conver2Diary(HttpServletRequest req) {
        ActivityDiary diary = new ActivityDiary();
        diary.setActivityId(WebUtils.paramLong(req, "activityId", 0));
        diary.setTopicUrl(WebUtils.param(req, "diary_url", ""));
        diary.setDiaryId(WebUtils.paramLong(req, "diaryId", 0));
        diary.setClubId(WebUtils.paramLong(req, "clubId", 0));
        diary.setBeginAt(WebUtils.parseDate(WebUtils.param(req, "beginDate", "")));
        diary.setCityId(WebUtils.paramInt(req, "cityId", 0));
        diary.setCityName(WebUtils.getAreaPlaceByReq(req, "cityName", ""));
        diary.setProvinceId(WebUtils.paramInt(req, "provinceId", 0));
        diary.setProvinceName(WebUtils.param(req, "provinceName", ""));
        return diary;
    }

    /**
     * 删除指定活动日记
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/activity/delActivityDiary.do", method = RequestMethod.POST)
    public void delActivityDiary(HttpServletRequest req, HttpServletResponse resp) {
        long diaryId = WebUtils.paramLong(req, "diaryId", 0);
        if (diaryId < 1) {
            errorMsg(resp, "参数错误", "");
        }
        this.hasRight(req, resp);
        ActivityDiary diary = activityService.getDiaryById(diaryId);
        if (diary != null) {
            if (activityService.delDiaryByDiayId(diary, diaryId)) {
//                //如果一篇日记，该车友会油值减10L
//                activityService.addOilToClub(activityId, 1, false);
                successMsg(resp, "删除成功");
            } else {
                errorMsg(resp, "删除失败", "");
            }
        } else {
            errorMsg(resp, "日记不存在", "");
        }
    }

    /**
     * 活动报名人员清单下载
     *
     * @param req
     * @param resp
     * @return
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    @RequestMapping(value = "/activity/reglistexport.do")
    public String reglistexport(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Activity activity = activityService.findById(activityId);
        Club club = clubService.getValidClub(clubId);
        if (activityId < 1 || club == null || activity == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--findByactIdClubId!", ex);
            }
        }
        if (!hasRight(req, resp)) {
            return null;
        }
        String filename = URLEncoder.encode("reglist", "UTF-8") + "_";
        OutputStream os = null;
        List<ActivityMember> listMember = activityService.listMemberByActivitiId(activityId, ActivityMember.STATUS_PASS);
        try {
            if (null != listMember && !listMember.isEmpty()) {
                os = resp.getOutputStream();
                // 清空输出流
                resp.reset();
                // 定义输出类型
                resp.setContentType("application/vnd.ms-excel");
                resp.setHeader("Content-disposition", "attachment; filename=" + new String((filename + ".xls").getBytes(), "UTF-8"));
                List<Map<String, Object>> rows = new ArrayList(listMember.size());
                int i = 0;
                int num = 0;
                for (ActivityMember a : listMember) {
                    HashMap<String, Object> row = new HashMap<String, Object>();
                    row.put("编号", ++i);
                    row.put("论坛昵称", a.getNikename());
                    row.put("姓名", null == a.getName() ? "" : a.getName());
                    row.put("电话", null == a.getPhone() ? "" : a.getPhone());
                    row.put("参加人数", 0 == a.getJoinNum() ? "" : a.getJoinNum());
                    num += a.getJoinNum();
                    row.put("车牌号", null == a.getLincensePlate() ? "" : a.getLincensePlate());
                    row.put("备注", null == a.getDescript() ? "" : a.getDescript());
                    row.put("加入时间", null == a.getCreateAt() ? "" : DateUtils.format(a.getCreateAt()));
                    rows.add(row);
                }
                List<String> cols = Arrays.asList("编号", "论坛昵称", "姓名", "电话", "参加人数", "车牌号", "备注", "加入时间");
                //统计
                HashMap<String, Object> total = new HashMap<String, Object>();
                total.put("编号", String.format("共计%s人", i));
                total.put("参加人数", String.format("共计%s人", num));
                rows.add(total);
                ExcelGenerator.generate(rows, os, cols);
                os.flush();
                os.close();
            }
            resp.setHeader("Content-disposition", "attachment; filename=" + new String((filename + ".xls").getBytes(), "UTF-8"));
        } catch (IOException ex) {
            log.error("reglistexport fail--IOException!", ex);
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException ex) {
                log.error("reglistexport fail when clos outputStream!", ex);
            }
        }
        return null;
    }

    /**
     * 活动表单验证
     *
     * @param activity
     * @param resp
     * @
     */
    private boolean checkActivity(Activity activity, HttpServletResponse resp) {
        String nameMsg = this.checkName(activity.getTitle());
        if (StringUtils.isBlank(activity.getPicUrl()) || (activity.getPicUrl().equals(defalutImg))) {
            errorMsg(resp, "请上传活动封面图", "");
            return false;
        } else if (!nameMsg.equals("true")) {
            errorMsg(resp, nameMsg, "");
            return false;
        } else if (activity.getBeginDate() == null) {
            errorMsg(resp, "请选择活动开始时间", "");
            return false;
        } else if (activity.getEndDate() == null) {
            errorMsg(resp, "请选择活动结束时间", "");
            return false;
        } else if (activity.getSignupDate() == null) {
            errorMsg(resp, "请选择活动报名截止时间", "");
            return false;
        } else if (activity.getJoinNum() < 0) {
            errorMsg(resp, "活动费用不能小于0", "");
            return false;
        } 
        return true;
    }
    
    /**
     * 检查电话
     * @param req
     * @param resp
     * @return
     */
    private boolean checkPhone(String phone, HttpServletResponse resp){
         if (StringUtils.isBlank(phone)) {
             errorMsg(resp, "请填写手机", "phone");
             return false;
         }
         if (!phone.matches(Regex.cellphone.value)
                 || phone.matches(Regex.specialPhone.value)) {
             errorMsg(resp, "请填写合法的手机", "phone");
             return false;
         }
         return true;
    }

    /**
     * 对象转换
     *
     * @param req
     * @return
     */
    private Activity convertActivity(HttpServletRequest req) {
        Activity activity = new Activity();
        activity.setType(WebUtils.paramInt(req,"clubType", 0 ));
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        activity.setActivityId(activityId);
        activity.setClubId(WebUtils.paramLong(req, "clubId", 0));
        activity.setTitle(WebUtils.param(req, "title", "").trim());
        activity.setContext(WebUtils.param(req, "context", "").trim());
        activity.setFullContent(WebUtils.param(req, "context", "").trim());
        activity.setBeginDate(WebUtils.parseDate(req, "beginDate"));
        activity.setEndDate(WebUtils.parseDate(req, "endDate"));
        activity.setSignupDate(WebUtils.parseDate(req, "signupDate"));
        activity.setLongContext(WebUtils.paramInt(req, "longContext", 0));
        activity.setMoney(WebUtils.paramInt(req, "money", 0));
        activity.setPicUrl(WebUtils.param(req, "picUrl", "").trim());
        //修改活动时报名人数不变
        if(activityId > 0) {
        	Activity oldaActivity = activityService.findById(activityId);
        	if(oldaActivity != null) {
        		activity.setJoinNum(oldaActivity.getJoinNum());
        	}
        } else {
        	activity.setJoinNum(WebUtils.paramInt(req, "joinNum", 0));
        }
        activity.setMaxJoin(WebUtils.paramInt(req, "maxJoin", 0));
        activity.setCreateBy(WebUtils.paramInt(req, "createBy", 0));
        activity.setCreateAt(WebUtils.parseDate( req, "createAt"));
        activity.setStatus(Activity.STATUS_YES);
        return activity;
    }
    
    /**
     * 获取活动图片
     * @param req
     * @return
     */
    private List<ActivityPic> converActivityPics(HttpServletRequest req){
    	List<ActivityPic> list = new ArrayList<ActivityPic>();
    	JSONArray picArray = WebUtils.parseArray(req, "picsJson");
    	if(picArray==null) return list;
    	for( int i = 0; i < picArray.size(); i++ ) {
    		JSONObject o = JSONObject.parseObject(picArray.getString(i));
    		ActivityPic pic = new ActivityPic();
    		pic.setUrl( o.getString("activityPic"));
	        pic.setDescription(o.getString("describe"));
	        pic.setWidth(o.getInteger("actpicWidth"));
	        pic.setHeight(o.getInteger("actpicHeight"));
	        int j = i+1;
	        pic.setSeq(j);
	        list.add(pic);
        }
    	return list;
    	
    }
    
    /**
     * 获取活动地址
     * @param req
     * @param type
     * @return
     */
    private List<ActivityPlace> convertActivityPlace(HttpServletRequest req,int type){
  	  List<ActivityPlace> activityPlaces = new ArrayList<ActivityPlace>();
  	  
  	  try {
  	    if(type == ActivityPlace.TYPE_GATHERING){
  	    	String name = WebUtils.param(req, "gathering","");
  	    	double Longitude = WebUtils.paramDouble( req, "loadjhdlongitude", 0);
  	    	double latitude = WebUtils.paramDouble( req, "loadjhdlatitude", 0);
  	    	String markName =WebUtils.paramTrim( req, "gatheringMarkName", "");
  	    	if(StringUtils.isBlank( name) || Longitude ==0 || latitude==0) return activityPlaces;
  	    	ActivityPlace activityPlace = new ActivityPlace();
   	       	activityPlace.setLatitude(latitude);
   	       	activityPlace.setLongitude(Longitude);
   	       	activityPlace.setName(name);
   	       	activityPlace.setType(ActivityPlace.TYPE_GATHERING);
   	       	activityPlace.setMarkName(markName);
   	       	activityPlaces.add( activityPlace );
  	      }else if(type==ActivityPlace.TYPE_DESTINATION){
  	    	  String[] names = req.getParameterValues("destination");
  	    	  String[] longitudeStr = req.getParameterValues("loadmddlongitude");
  	    	  String[] latitudeStr = req.getParameterValues("loadmddlatitude");
  	    	  String[] markNames = req.getParameterValues("destinationMarkName");
  	    	  if(names==null || longitudeStr==null || latitudeStr ==null){
  	    		  return activityPlaces;
  	    	  }
  	    	  if(names.length!=longitudeStr.length||names.length!=latitudeStr.length){
  	    		  log.error("创建活动，目的地数据错误");
  	    	  }else{
  	    		  for( int i = 0; i < names.length; i++ ) {
  	    			String name =StringUtils.trim(names[i]);
  	    			double Longitude = NumberUtils.toDouble(longitudeStr[i],0);
  	    			double latitude = NumberUtils.toDouble(latitudeStr[i],0);
  	    			if(StringUtils.isBlank( name) || Longitude ==0 || latitude==0) continue;
  	    			ActivityPlace activityPlace = new ActivityPlace();
  	    			activityPlace.setLatitude(latitude);
 		         	activityPlace.setLongitude(Longitude);
 		         	activityPlace.setName(name);
 		            activityPlace.setType(ActivityPlace.TYPE_DESTINATION);
 		            //别名
 		            if(markNames!=null && markNames[i]!=null){
 		            	activityPlace.setMarkName(markNames[i]);
 		            }
 		           activityPlaces.add( activityPlace );
                }
  	    	  }
  	      }
      }
      catch( Exception e ) {
      	log.error("app create Activity : change ActivityPlace to Json throw Exception ",e);
  	    return Collections.emptyList();
      }
  	  return activityPlaces;
    }

    /**
     * 活动申请表单验证
     *
     * @param member
     * @param resp
     * @return
     * @
     */
    private boolean checkAcMember(ActivityMember member, HttpServletResponse resp) {
        if (StringUtils.isBlank(member.getName())) {
            errorMsg(resp, "请输入真实姓名", "");
            return false;
        } else if (member.getName().length() > 20) {
            errorMsg(resp, "姓名长度不能超过20", "");
            return false;
        } else if (StringUtils.isBlank(member.getPhone())) {
            errorMsg(resp, "请输入联系电话", "");
            return false;
        } else if (member.getPhone().length() > 20) {
            errorMsg(resp, "电话长度不能超过20", "");
            return false;
        } else if (member.getJoinNum() < 1) {
            errorMsg(resp, "请输入正确的人数", "");
            return false;
        } else if (member.getLincensePlate().length() > 20) {
            errorMsg(resp, "车牌长度不能超过20", "");
            return false;
        } else if (member.getDescript().length() > 255) {
            errorMsg(resp, "备注长度不能超过255", "");
            return false;
        }
        return true;
    }

    private ActivityMember convertoAcMember(long activityId, long memberId, HttpServletRequest req) {
        ActivityMember activityMember = new ActivityMember();
        activityMember.setActivityId(activityId);
        activityMember.setUserId(memberId);
        activityMember.setName(WebUtils.param(req, "name", "").trim());
        activityMember.setPhone(WebUtils.param(req, "phone", "").trim());
        activityMember.setJoinNum(WebUtils.paramInt(req, "joinNum", 0));
        activityMember.setLincensePlate(WebUtils.param(req, "lincensePlate", "").trim());
        activityMember.setDescript(WebUtils.param(req, "descript", "").trim());
        activityMember.setCreateAt(DateUtils.getNow());
        activityMember.setStatus(ActivityMember.STATUS_APPLY);
        activityMember.setIsDriving(WebUtils.paramInt(req, "isDriving", ActivityMember.ISDRIVING_YES));
        return activityMember;
    }

    /**
     * 根据车友会ID返回活动列表
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/activity/listActivityByClubId.do", method = RequestMethod.GET)
    public void listActivityByClubId(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20, MIN_PAGESIZE, MAX_PAGESIZE);
        String callback = WebUtils.param(req, "callback", "");
        long userId = WebUtils.paramLong(req, "userId", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);

        Club club = clubService.getValidClub(clubId);
        JSONObject json = new JSONObject();
        json.put("clubId", clubId);
        if (club != null) {
            ClubMember member = memberService.findMember(userId, clubId);
            long memberId = 0;
            if (member != null) {
                memberId = member.getId();
            }
            json.put("clubName", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
            JSONArray jsonAlbum = new JSONArray();
            Pager<Activity> pager = activityService.pageForList(memberId, clubId, false, pageNo, pageSize);
            if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
                for (Activity activity : pager.getResultList()) {
                    JSONObject jsonContent = new JSONObject();
                    jsonContent.put("activityId", activity.getActivityId());
                    jsonContent.put("title", EncodeUtils.encodeForHTML(activity.getTitle(), sourceAgent));
                    jsonContent.put("signupDate", activity.getSignupDate().getTime());
                    jsonContent.put("beginDate", activity.getBeginDate().getTime());
                    jsonContent.put("endDate", activity.getEndDate().getTime());
                    jsonContent.put("pic", EncodeUtils.encodeForHTML(activity.getUrl160x120(), sourceAgent));
                    jsonContent.put("limitCount", activity.getMaxJoin());
                    Map<String, String> map = activityService.getListActivityStatus(memberId, activity);
                    jsonContent.put("statusCode", map.get("code"));
                    jsonContent.put("statusMsg", map.get("msg"));
                    boolean isSignUp = false; // 是否已经报名
                    if (userId > 0) {
                        if (member != null && activityService.isSignUp(activity.getActivityId(), memberId) != null) {
                            isSignUp = true;
                        }
                    }
                    int activityStatus = getActivityStatus(activity);//活动状态
                    jsonContent.put("activityStatus", activityStatus);
                    String place;
                    place = activity.getActivityPlace();
                    jsonContent.put("place", StringUtils.isEmpty(place) ? "" : EncodeUtils.encodeForHTML(place, sourceAgent));
                    jsonContent.put("isSignUp", isSignUp);
                    jsonAlbum.add(jsonContent);
                }
            }
            json.put("data", jsonAlbum);
            json.put("pageNo", pager.getPageNo());
            json.put("totalCount", pager.getPageCount());
            json.put("pageSize", pager.getPageSize());
            json.put("total", pager.getTotal());
            AppUtils.setSuccessCode(json);
        } else {
            AppUtils.setDataErrorCode(json, "该车友会ID不存在");
        }
        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json + ")");
            } else {
                print.println(json);
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("listActivityByClubId fail!", ex);
        }

    }

    /**
     * 根据用户ID返回活动列表
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/activity/listActivityByUserId.do", method = RequestMethod.GET)
    public JSONObject listActivityByUserId(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long userId = WebUtils.paramLong(req, "userId", 0);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20, MIN_PAGESIZE, MAX_PAGESIZE);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);

        User user = userService.findUser(userId);

        JSONObject json = new JSONObject();
        if (userId > 0 && user != null) {
            json.put("userId", user.getUid());
            JSONArray jsonAlbum = new JSONArray();
            Pager<Activity> pager = activityService.pageMyJoinActivity(userId, 0, true, pageNo, pageSize);
            if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
                for (Activity activity : pager.getResultList()) {
                    Club club = clubService.getValidClub(activity.getClubId());
                    if (club != null) {
                        JSONObject jsonContent = new JSONObject();
                        ClubMember member = memberService.findMember(userId, activity.getClubId());
                        jsonContent.put("activityId", activity.getActivityId());
                        jsonContent.put("clubName", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
                        jsonContent.put("clubId", activity.getClubId());
                        jsonContent.put("title", EncodeUtils.encodeForHTML(activity.getTitle(), sourceAgent));
                        jsonContent.put("signupDate", activity.getSignupDate().getTime());
                        jsonContent.put("beginDate", activity.getBeginDate().getTime());
                        jsonContent.put("endDate", activity.getEndDate().getTime());
                        jsonContent.put("pic", EncodeUtils.encodeForHTML(activity.getUrl120x120(), sourceAgent));
                        Map<String, String> map = activityService.getListActivityStatus(member.getId(), activity);
                        jsonContent.put("statusCode", map.get("code"));
                        jsonContent.put("statusMsg", map.get("msg"));
                        boolean isSignUp = false;
                        if (user != null && userId > 0) {
                            if (member != null && activityService.isSignUp(activity.getActivityId(), member.getId()) != null) {
                                isSignUp = true;
                            }
                        }

                        String place;
                        if (activity.getOnlineStatus() > 0) {
                            place = "线上";
                        } else {
                            String provinceName = activity.getProvinceName() == null ? "" : activity.getProvinceName();
                            String cityName = activity.getCityName() == null ? "" : activity.getCityName();
                            place = provinceName + cityName;
                        }

                        jsonContent.put("place", StringUtils.isEmpty(place) ? "" : EncodeUtils.encodeForHTML(place, sourceAgent));
                        jsonContent.put("isSignUp", isSignUp);
                        jsonAlbum.add(jsonContent);
                    }
                }
            }
            json.put("data", jsonAlbum);
            json.put("pageNo", pager.getPageNo());
            json.put("pageSize", pager.getPageSize());
            json.put("total", pager.getTotal());
            AppUtils.setSuccessCode(json);
        } else {
            AppUtils.setDataErrorCode(json, "用户不存在");
        }
        return json;
    }

    /**
     * 根据活动ID返回活动详情
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/activity/getActivityById.do", method = RequestMethod.GET)
    public JSONObject getActivityById(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        long userId = WebUtils.paramLong(req, "userId", 0);
        User user = null;
        if (userId > 0) {
            user = userService.findUser(userId);
        }

        Activity activity = activityService.findById(activityId);
        JSONObject json = new JSONObject();
        json.put("activityId", activityId);
        if (activity != null) {
            json.put("title", EncodeUtils.encodeForHTML(activity.getTitle(), sourceAgent));
            json.put("clubId", activity.getClubId());
            boolean isSingnUp = false;
            ClubMember userMember = null;
            if (user != null && user.getUid() > 0) {
                userMember = memberService.findMember(user.getUid(), activity.getClubId());
                if (userMember != null) {
                    if (activityService.isSignUp(activity.getActivityId(), userMember.getId()) != null) {
                        isSingnUp = true;
                    }
                }
                json.put("memberId", userMember == null ? 0 : userMember.getId());
            }
            json.put("adminType", clubService.getClubRelationByUser(user, activity.getClubId()));
            json.put("isSignUp", isSingnUp);
            User userBy = userService.findUser(activity.getCreateBy());
            String createBy = "管理员";
            if (userBy != null) {
                createBy = userBy.getNickname();
            }
            json.put("createBy", createBy);
            json.put("createAt", activity.getCreateAt().getTime());
            json.put("beginDate", activity.getBeginDate().getTime());
            json.put("endDate", activity.getEndDate().getTime());
            json.put("signupDate", activity.getSignupDate().getTime());
            String place;
            if (activity.getOnlineStatus() > 0) {
                place = "线上";
            } else {
            	String provinceName = activity.getProvinceName() == null ? "" : activity.getProvinceName();
            	String cityName = activity.getCityName() == null ? "" : activity.getCityName();
                place = provinceName + cityName;
            }
            json.put("place", StringUtils.isEmpty(place) ? "" : EncodeUtils.encodeForHTML(place, sourceAgent));
            json.put("money", activity.getMoney());
            String content = activityService.getTotalActivityTxt(activityId);
            json.put("content", StringUtil.filterUbbCode(content));
            List<ActivityMember> listMember = activityService.listMemberByActivitiId(activityId, ActivityMember.STATUS_PASS);
            List<ActivityMember> listApply = activityService.listMemberByActivitiId(activityId, ActivityMember.STATUS_APPLY);
            json.put("apply", this.AcitivityToJson(listApply, sourceAgent));
            json.put("pass", this.AcitivityToJson(listMember, sourceAgent));
            json.put("limitCount", activity.getMaxJoin());
            Map<String, String> map = activityService.getDetailActivityStatus(userMember == null ? 0 : userMember.getId(), activityId);
            json.put("statusCode", map.get("code"));
            json.put("statusMsg", map.get("msg"));
            json.put("applysCount", activityService.countActivityMemberByStatus(activityId, ActivityMember.STATUS_APPLY));
            JSONArray jsonArray = new JSONArray();
            if (listMember != null && !listMember.isEmpty()) {
                for (ActivityMember member : listMember) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("name", EncodeUtils.encodeForHTML(member.getName(), sourceAgent));
                    jsonObject.put("nickname", EncodeUtils.encodeForHTML(member.getNikename(), sourceAgent));
                    jsonObject.put("joinNum", member.getJoinNum());
                    jsonObject.put("phone", EncodeUtils.encodeForHTML(member.getPhone(), sourceAgent));
                    jsonObject.put("descript", member.getDescript());
                    jsonObject.put("lincensePlate", member.getLincensePlate());
                    ClubMember clubMember = memberService.find(member.getUserId());
                    String url = "";
                    long uid = 0;
                    if (clubMember != null) {
                        url = systemConfig.getUcRoot() + "/" + clubMember.getUid() + "/";
                        uid = clubMember.getUid();
                    }
                    jsonObject.put("userId", uid);
                    jsonObject.put("memberId", member.getUserId());
                    jsonObject.put("pic", url);
                    jsonArray.add(jsonObject);
                }
            }
            AppUtils.setSuccessCode(json);
            json.put("data", jsonArray);
        } else {
            AppUtils.setDataErrorCode(json, "该活动ID不存在");
        }
        return json;
    }

    /**
     * 根据活动ID返回活动详情(带缓存)
     *
     * @throws
     */
    @RequestMapping(value = "/activity/getActivityByIdForCache.do", method = RequestMethod.GET)
    public void getActivityByIdForCache(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setCacheHeader(resp, 3600);
        WebUtils.setEncoding(req, resp);
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        long userId = WebUtils.paramLong(req, "userId", 0);
        String callback = WebUtils.param(req, "callback", "");
        User user = null;
        if (userId > 0) {
            user = userService.findUser(userId);
        }

        Activity activity = activityService.findById(activityId);
        JSONObject json = new JSONObject();
        json.put("activityId", activityId);
        if (activity != null) {
            json.put("title", EncodeUtils.encodeForHTML(activity.getTitle(), sourceAgent));
            json.put("clubId", activity.getClubId());
            boolean isSingnUp = false;
            ClubMember userMember = null;
            if (user != null && user.getUid() > 0) {
                userMember = memberService.findMember(user.getUid(), activity.getClubId());
                if (userMember != null) {
                    if (activityService.isSignUp(activity.getActivityId(), userMember.getId()) != null) {
                        isSingnUp = true;
                    }
                }
                json.put("memberId", userMember == null ? 0 : userMember.getId());
            }
            json.put("isSignUp", isSingnUp);
            User userBy = userService.findUser(activity.getCreateBy());
            String createBy = "管理员";
            if (userBy != null) {
                createBy = userBy.getNickname();
            }
            json.put("createBy", createBy);
            json.put("createAt", activity.getCreateAt().getTime());
            json.put("beginDate", activity.getBeginDate().getTime());
            json.put("endDate", activity.getEndDate().getTime());
            json.put("signupDate", activity.getSignupDate().getTime());
            String place;
            if (activity.getOnlineStatus() > 0) {
                place = "线上";
            } else {
                String provinceName = activity.getProvinceName() == null ? "" : activity.getProvinceName();
                String cityName = activity.getCityName() == null ? "" : activity.getCityName();
                place = provinceName + cityName;
            }
            json.put("place", StringUtils.isEmpty(place) ? "" : EncodeUtils.encodeForHTML(place, sourceAgent));
            json.put("money", activity.getMoney());
            String content = activityService.getTotalActivityTxt(activityId);
            json.put("content", StringUtil.byteSubstring4Reply(content, StringUtil.length(content) * 1000));
            json.put("limitCount", activity.getMaxJoin());
            Map<String, String> map = activityService.getDetailActivityStatus(userMember == null ? 0 : userMember.getId(), activityId);
            json.put("statusCode", map.get("code"));
            json.put("statusMsg", map.get("msg"));
            json.put("applysCount", activityService.countActivityMemberByStatus(activityId, ActivityMember.STATUS_APPLY));
            AppUtils.setSuccessCode(json);
        } else {
            AppUtils.setDataErrorCode(json, "该活动ID不存在");
        }
        try {
            PrintWriter out = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                out.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json + ")");
            } else {
                out.println(json);
            }
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getActivityByIdForCache fail!", ex);
        }

    }

    /**
     * 报名参加活动对象转jsonArray
     *
     * @param list
     * @return
     */
    public JSONArray AcitivityToJson(List<ActivityMember> list, int sourceAgent) {
        JSONArray jsonArray = new JSONArray();
        if (list != null && !list.isEmpty()) {
            for (ActivityMember member : list) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", EncodeUtils.encodeForHTML(member.getName(), sourceAgent));
                jsonObject.put("nickname", EncodeUtils.encodeForHTML(member.getNikename(), sourceAgent));
                jsonObject.put("joinNum", member.getJoinNum());
                jsonObject.put("phone", EncodeUtils.encodeForHTML(member.getPhone(), sourceAgent));
                jsonObject.put("descript", member.getDescript());
                jsonObject.put("lincensePlate", member.getLincensePlate());
                ClubMember clubMember = memberService.find(member.getUserId());
                String url = "";
                long uid = 0;
                if (clubMember != null) {
                    url = systemConfig.getUcRoot() + "/" + clubMember.getUid() + "/";
                    uid = clubMember.getUid();
                }
                jsonObject.put("userId", uid);
                jsonObject.put("memberId", member.getUserId());
                jsonObject.put("pic", url);
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }

    /**
     * 活动报名接口
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/activity/applyActivity.do", method = RequestMethod.POST)
    public JSONObject applyActivity(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        User user = userAuth.getUser(req, resp);
        Activity activity = activityService.findById(activityId);
        JSONObject json = new JSONObject();
        json.put("activityId", activityId);
        int code = -1;
        String message;
        if (user != null && user.getUid() > 0) {
            if (activity != null) {
                long now = System.currentTimeMillis();
                if (activity.getMaxJoin() == 0 || activity.getJoinNum() < activity.getMaxJoin()) {
                    if (!(now > activity.getSignupDate().getTime())) {
                        ClubMember clubMember = memberService.findMember(user.getUid(), activity.getClubId());
                        if (clubMember != null) {
                            ActivityMember member = this.convertoAcMember(activityId, clubMember.getId(), req);
                            member.setNikename(user.getNickname());
                            String result = this.inifcheckAcMember(member);
                            if (result.equals("true")) {
                                long i = activityService.createActityMember(member);
                                if (i > 0) {
                                    activityService.refshActivityJoinNum(activityId, activity.getClubId());
                                    //给管理员发送审核消息
                                    Club club = clubService.getValidClub(activity.getClubId());
                                    if (club != null) {
                                        List<ClubMember> listMember = memberService.listAdmins(club.getClubId());
                                        String activityUrl = messageService.assembleClubUrl(club.getClubUrl() + "/activity/a" + activityId, activity.getTitle());
                                        if (club != null && listMember != null && !listMember.isEmpty()) {
                                            for (ClubMember adminMember : listMember) {
                                                messageService.send(userService.findUser(adminMember.getUid()), MessageService.ACTIVITY_APPLY, activityUrl, member.getName());
                                            }
                                        }
                                    }
                                    code = 0;
                                    message = "报名成功";
                                } else {
                                    message = "报名失败";
                                }
                            } else {
                                message = result;
                            }
                        } else {
                            code = AppUtils.STATUS_PERMISSIONS_ERROR;
                            message = "只有该车友会会员才能报名哦！";
                        }
                    } else {
                        code = AppUtils.STATUS_DATA_ERROR;
                        message = "报名已截止！";
                    }
                } else {
                    code = AppUtils.STATUS_FAIL;
                    message = "报名人数已满，请联系管理员！";
                }

            } else {
                code = AppUtils.STATUS_DATA_ERROR;
                message = "活动ID不存在";
            }
        } else {
            code = AppUtils.STATUS_NOLOGIN_ERROR;
            message = "用户未登录";
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 取消报名(APP用)
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/activity/cancelActivity.do", method = RequestMethod.POST)
    public JSONObject cancelActivity(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        User user = userAuth.getUser(req, resp);
        JSONObject json = new JSONObject();
        int code;
        String message;
        if (user != null && user.getUid() > 0) {
            Activity activity = activityService.findById(activityId);
            if (activity != null) {
                ClubMember member = memberService.findMember(user.getUid(), activity.getClubId());
                if (member != null) {
                    if (activity.getSignupDate().after(new Date())) {
                        long i = activityService.deleteActityMember(activityId, member.getId());
                        if (i > 0) {
                            activityService.refshActivityJoinNum(activityId, activity.getClubId());
                            code = 0;
                            message = "取消成功";
                            
                            //获取车友会
                            Club club = clubService.getClub(activity.getClubId());
                            String clubUrl = "";
                            if(club != null) {
                            	clubUrl = club.getClubUrl();
                            }
                            //取消活动报名发消息给活动发布者
                            User adminUser = userService.findUser(activity.getCreateBy());
                            messageService.send(adminUser, MessageService.ACT_APPLY_CANCEL,
                                    messageService.assembleUserUrl(user.getUid(), user.getNickname()), 
                                    messageService.assembleActivityUrl(clubUrl, activityId, activity.getTitle()));
                        } else {
                            code = AppUtils.STATUS_FAIL;
                            message = "取消失败";
                        }
                    } else {
                        code = AppUtils.STATUS_FAIL;
                        message = "报名时间已截止，不能取消报名！";
                    }
                } else {
                    code = AppUtils.STATUS_DATA_ERROR;
                    message = "操作失败，您已被管理员移出车友会！";
                }
            } else {
                code = AppUtils.STATUS_DATA_ERROR;
                message = "活动ID不存在";
            }
        } else {
            code = AppUtils.STATUS_NOLOGIN_ERROR;
            message = "用户未登录";
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 接口验证活动报名字段
     *
     * @param member
     * @return
     */
    private String inifcheckAcMember(ActivityMember member) {
        if (StringUtils.isBlank(member.getName())) {
            return "请输入真实姓名";
        } else if (member.getName().length() > 20) {
            return "姓名长度不能超过20";
        } else if (StringUtils.isBlank(member.getPhone())) {
            return "请输入联系电话";
        } else if (member.getPhone().length() > 20) {
            return "电话长度不能超过20";
        } else if (member.getJoinNum() < 1) {
            return "请输入正确的人数";
        } else if (member.getLincensePlate().length() > 20) {
            return "车牌长度不能超过20";
        } else if (member.getDescript().length() > 255) {
            return "备注长度不能超过255";
        }
        return "true";
    }

    /**
     * 活动名称验证
     *
     * @param name
     * @return
     */
    public String checkName(String name) {
        if (StringUtils.isBlank(name)) {
            return "请输入活动名称";
        } else if (StringUtil.length(name) > Activity.TITLE_SIZE) {
            return "最多30个字";
        } else {
            return "true";
        }
    }

    /**
     * 活动名称动态验证
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/activity/checkAcName.do", method = RequestMethod.GET)
    public JSONObject checkAcName(HttpServletRequest req, HttpServletResponse resp) {
        String name = WebUtils.param(req, "name", "");
        String retNameMsg = this.checkName(name);
        JSONObject json = new JSONObject();
        int code = -1;
        String msg;
        if (!"true".equals(retNameMsg)) {
            msg = retNameMsg;
        } else {
            code = 1;
            msg = "验证通过";
        }
        json.put("code", code);
        json.put("message", msg);
        return json;
    }

    /**
     * WAP活动详情
     *
     * @param req
     * @param resp
     * @return Created by guoqiang, 2014-01-24
     */
    @RequestMapping(value = "/wap/activity/detail.do", method = RequestMethod.GET)
    public String detailActivityForWap(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Activity activity = activityService.findById(activityId);
        if (activity == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--findByactIdClubId!", ex);
            }
        }
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--getValidClub!", ex);
            }
        }
        User user = userAuth.getUser(req, resp);
        ClubMember member = memberService.findMember(user.getUid(), clubId);
        //完整内容
        if (activity != null) {
            activity.setFullContent(activityService.getTotalActivityTxt(activityId));
            activity.setUserActivityStatus(activityService.getDetailActivityStatus(member == null ? 0 : member.getId(), activityId).get("code"));
        }
        //该活动参加的人员列表
        List<ActivityMember> listMember = activityService.listMemberByActivitiId(activityId, ActivityMember.STATUS_PASS);
        List<ActivityMember> listApply = activityService.listMemberByActivitiId(activityId, ActivityMember.STATUS_APPLY);
        //活动日记
//      Pager<ActivityDiary> listDiary = activityService.pageActivityDiary(0,clubId,0,pageNo, pageSize);
        req.setAttribute("address", activity.getActivityPlace());
        req.setAttribute("userStatus", activity.getUserActivityStatus());
        req.setAttribute("activityStatus", getActivityStatus(activity));
        req.setAttribute("user", user);
        req.setAttribute("club", club);
        req.setAttribute("member", member);
        req.setAttribute("clubId", clubId);
        req.setAttribute("activity", activity);
        req.setAttribute("listMember", listMember);
        req.setAttribute("listApply", listApply);
//        req.setAttribute("listDiary", listDiary);
//        req.setAttribute("listMyAct", listMyAct);
//        req.setAttribute("listHostAct", listHostAct);

        return "template/wap/activity/activity_details";
    }

    /**
     * 获取活动状态 status 0:接受报名，1：报名已截止，2；活动已开始， －1：活动已经结束
     */
    private int getActivityStatus(Activity activity) {
        Date now = DateUtils.getNow();

        if (!now.after(activity.getEndDate())) {//活动还没结束
            if ((now.getTime() <= activity.getSignupDate().getTime())) { //活动未开始 且 报名未结束
                return 0;
            } else if (activity.getSignupDate().getTime() < now.getTime() && activity.getBeginDate().getTime() > now.getTime()) {
                return 1;
            } else {
                return 2;
            }
        } else {
            return -1;
        }
    }

    /**
     * 返回活动状态描述
     *
     * @param status
     * @return
     */
    private String getStatusDesc(int status) {
        String result = "";
        if (status == -1) {
            result = "活动已结束";
        } else if (status == 0) {
            result = "报名中";
        } else if (status == 1) {
            result = "报名已结束";
        } else if (status == 2) {
            result = "活动中";
        }
        return result;
    }

    /**
     * 活动列表
     *
     * @param req
     * @param resp
     * @return Created by guoqiang, 2014-01-22
     */
    @RequestMapping(value = "/wap/activity/list.do", method = RequestMethod.GET)
    public String listWapActivity(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("redirect to error page fail--getValidClub!", ex);
            }
        }

        User user = userAuth.getUser(req, resp);
        ClubMember member = memberService.findMember(user.getUid(), clubId);
        req.setAttribute("user", user);
        req.setAttribute("club", club);
        req.setAttribute("clubId", clubId);
        req.setAttribute("member", member);

        return "template/wap/activity/activity_list";
    }

    /**
     * 根据活动ID数组返回数据，前端热门活动版块调用
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/activity/listActivityByIds.do", method = RequestMethod.GET)
    public void listActivityByIds(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("GBK");
        resp.setContentType("text/html; charset=GBK");
        String originHeader = req.getHeader("Origin");
        if (StringUtils.isNotBlank(originHeader)) {
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        String ids = WebUtils.param(req, "ids", "");
        String callback = WebUtils.param(req, "callback", "");
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        if (ids.endsWith(",")) {
            ids = ids.substring(0, ids.length() - 1);
        }
        List<Activity> list = activityService.listActivityByIds(ids);
        JSONObject json = new JSONObject();
        if (list != null && !list.isEmpty()) {
            JSONArray arry = new JSONArray();
            for (Activity activity : list) {
                JSONObject obj = new JSONObject();
                obj.put("activityId", activity.getActivityId());
                obj.put("title", activity.getTitle());
                obj.put("beginDate", DateUtils.format(activity.getBeginDate()));
                obj.put("endDate", DateUtils.format(activity.getEndDate()));
                obj.put("activityStatus", getStatusDesc(getActivityStatus(activity)));
                String place;
                if (activity.getOnlineStatus() > 0) {
                    place = "线上";
                } else {
                    String provinceName = activity.getProvinceName() == null ? "" : activity.getProvinceName();
                    String cityName = activity.getCityName() == null ? "" : activity.getCityName();
                    place = provinceName + cityName;
                }
                obj.put("place", StringUtils.isEmpty(place) ? "" : EncodeUtils.encodeForHTML(place, sourceAgent));
                String clubName = "";
                String url = "";
                Club club = clubService.getValidClub(activity.getClubId());
                if (club != null) {
                    clubName = club.getName();
                    url = systemConfig.getRoot() + "/" + club.getClubUrl() + "/";
                }
                obj.put("clubName", clubName);
                obj.put("url", url);
                arry.add(obj);
            }
            json.put("date", arry);
        }
        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("listActivityByIds fail!", ex);
        }
    }

    /**
     * ajax操作的错误信息提示
     *
     * @param resp
     * @param msg
     * @param field
     */
    private void errorMsg(HttpServletResponse resp, String msg, String field) {
        resp.setCharacterEncoding("UTF-8");
        try {
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", -1)
                    .put("field", field)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    private void successMsg(HttpServletResponse resp, String msg) {
        resp.setCharacterEncoding("UTF-8");
        try {
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", 200)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("set successMsg fail!", ex);
        }
    }

    /**
     * 活动审核列表（APP用）
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/activity/listActivityAudit.do", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject listActivityAudit(HttpServletRequest request, HttpServletResponse response) {
        long activityId = WebUtils.paramLong(request, "activityId", 0);
        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        Activity activity = activityService.findById(activityId);
        User user = userAuth.getUser(request, response);
        if (user != null && user.getUid() > 0) {
            if (activityId > 0 && activity != null) {
                if (memberService.isClubNormalAdmin(user.getUid(), activity.getClubId())) {
                    List<ActivityMember> activityMembers = activityService.listActivityAuditMembers(activityId);
                    if (activityMembers != null) {
                        for (ActivityMember m : activityMembers) {
                            JSONObject obj = new JSONObject();
                            obj.put("memberId", m.getUserId());
                            obj.put("nickname", m.getNikename());
                            ClubMember clubMember = memberService.find(m.getUserId());
                            obj.put("userId", clubMember == null ? 0 : clubMember.getUid());
                            obj.put("name", m.getName());
                            obj.put("phone", m.getPhone());
                            obj.put("joinNum", m.getJoinNum());
                            obj.put("lincensePlate", m.getLincensePlate());
                            obj.put("descript", m.getDescript());
                            array.add(obj);
                        }
                    }
                    json.put("data", array);
                    AppUtils.setSuccessCode(json);
                } else {
                    AppUtils.setPermissionsError(json, "只有管理员才能查看哦！");
                }

            } else {
                AppUtils.setDataErrorCode(json, "找不到该活动");
            }
        } else {
            AppUtils.setNoLoginCode(json);
        }

        return json;
    }

    /**
     * 热门日记，全车友会 给大首页论坛版块调用
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/activity/listHostActivityDiary", method = RequestMethod.GET)
    @ResponseBody
    public void listHostActivityDiary(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        WebUtils.setCacheHeader(response, 3600);//缓存1h
        int size = WebUtils.paramInt(request, "size", 10, MIN_PAGESIZE, MAX_PAGESIZE);
        String callback = WebUtils.param(request, "callback", "");
        String[] topicIdStr = WebUtils.param(request, "topicIds", "").split(",");
        int MAX_TOPICIDS = 10;
        int sourceAgent = WebUtils.paramInt(request, "source_agent", 2);
//        int maxSize = 400; //最大查询数量
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        Pager<ActivityDiary> pager;
        List<ActivityDiary> list;
        List<Long> topicIds = new ArrayList<Long>(topicIdStr.length);
        for (String s : topicIdStr) {
            try {
                long id = Long.parseLong(s);
                if (id > 0) {
                    topicIds.add(id);
                }
            } catch (java.lang.NumberFormatException e) {
            }
            if (topicIds.size() >= MAX_TOPICIDS) {
                break;
            }
        }
        if (topicIds.isEmpty()) {
            pager = activityService.pagerActivityDiary(0, 0, pageNo, size);
            list = pager.getResultList();
        } else {
            list = (activityService.getFirstDiaryByTopicIds(topicIds.toArray()));
            pager = new Pager<ActivityDiary>(list);
        }
        if (list != null && !list.isEmpty()) {
            for (ActivityDiary activityDiary : list) {
                JSONObject obj = new JSONObject();
                Club club = clubService.getClub(activityDiary.getClubId());
                if (club != null) {
                    obj.put("clubName", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
                    obj.put("logo", club.getLogo());
                    obj.put("clubUrl", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
                }
                obj.put("clubId", activityDiary.getClubId());
                obj.put("title", EncodeUtils.encodeForHTML(activityDiary.getTitle(), sourceAgent));
                obj.put("image1", activityDiary.getAppImage1());
                obj.put("image2", activityDiary.getAppImage2());
                obj.put("image3", activityDiary.getAppImage3());
                obj.put("content", EncodeUtils.encodeForHTML(activityDiary.getContent().length() > 108 ? activityDiary.getContent().substring(0, 108) + "...." : activityDiary.getContent(), sourceAgent));
                obj.put("topicId", activityDiary.getTopicId());
                Date beginAt = activityDiary.getBeginAt();
                obj.put("pubTime", beginAt == null ? 0 : beginAt.getTime());
                obj.put("nickname", EncodeUtils.encodeForHTML(activityDiary.getCreateName(), sourceAgent));
                obj.put("userId", activityDiary.getCreateBy());
                obj.put("topicUrl", activityDiary.getTopicUrl() == null ? "" : activityDiary.getTopicUrl());
                array.add(obj);
            }

        }
        AppUtils.setSuccessCode(json);
        json.put("data", array);
        json.put("pageNo", pager.getPageNo());
        json.put("pageCount", pager.getPageCount());
        json.put("total", pager.getTotal() > 400 ? 400 : pager.getTotal());
        try {
            PrintWriter print = response.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("listHostActivityDiary fail!", ex);
        }
    }

    /**
     * 是否可以加入活动
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/activity/isJoinActivity")
    @ResponseBody
    public void isJoinActivity(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long activityId = WebUtils.paramLong(request, "activityId", 0);
        long memberId = WebUtils.paramLong(request, "targetId", 0);
        String callback = WebUtils.param(request, "callback", "");
        Activity activity = activityService.findById(activityId);
        JSONObject json = new JSONObject();
        if (activity != null) {
            ClubMember member = memberService.find(memberId);
            if (member != null) {
                Map<String, String> map = activityService.getDetailActivityStatus(memberId, activityId);
                json.put("statusCode", map.get("code"));
                json.put("statusMsg", map.get("msg"));
                AppUtils.setSuccessCode(json);
            } else {
                AppUtils.setDataErrorCode(json, "找不到该会员");
            }
        } else {
            AppUtils.setDataErrorCode(json, "找不到该活动");
        }
        try {
            PrintWriter print = response.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("isJoinActivity fail!", ex);
        }
    }

    /**
     * 热门活动日记
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/index/listHostActivityDiary", method = RequestMethod.GET)
    public String listIndexHostActivityDiary(HttpServletRequest req, HttpServletResponse resp) {
        int MAX_SIZE = 400; //最大允许查出400条
        int pageSize = WebUtils.paramInt(req, "pageSize", 10, 1, MAX_SIZE);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1, 1, MAX_SIZE / pageSize);
        Pager<ActivityDiary> pager = activityService.pagerActivityDiary(0, 0, pageNo, pageSize);
        List<ActivityDiary> list = pager.getResultList();
        if (list != null) {
            for (ActivityDiary activityDiary : list) {
                Club club = clubService.getClub(activityDiary.getClubId());
                if (club != null) {
                    activityDiary.setClub(club);
                }
            }
        }
        pager.setTotal(Math.min(pager.getTotal(), MAX_SIZE));
        req.setAttribute("pager", pager);
        return "index/hotDiary";
    }
    
    /**
     * 活动路线图大页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/activity/placeMapPage.do", method = RequestMethod.GET)
    public String placeMapPage(HttpServletRequest request, HttpServletResponse response) {
    	 WebUtils.setEncoding(request, response);
         long activityId = WebUtils.paramLong(request, "activityId", 0);
         Activity activity = activityService.findById(activityId);
         if(activity == null) {
        	 try {
                 response.sendError(404);
                 return null;
             } catch (IOException ex) {
                 log.error("redirect to error page fail--placeMapPage!", ex);
             }
         }
         
         request.setAttribute("activityId", activityId);
         request.setAttribute("BAIDUMAPAK", systemConfig.getBaiduMapAk());
         return "template/activity/placeMapPage";
    }
}
